<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import dashboardApi from '@/api/dashboard.js'

const chart = ref(null)
const chartData = ref([])
const loading = ref(false)

// 错误类型配置
const errorTypes = [
  { key: 'unsupportedDsNum', name: '不支持DS记录', color: '#ff6b6b' },
  { key: 'unsupportedDnskeyNum', name: '不支持DNSKEY', color: '#4ecdc4' },
  { key: 'dnskeyMissingNum', name: 'DNSKEY缺失', color: '#45b7d1' },
  { key: 'rrsigMissingNum', name: 'RRSIG缺失', color: '#96ceb4' },
  { key: 'signatureNotValidNum', name: '签名无效', color: '#feca57' },
  { key: 'signatureExpiredNum', name: '签名过期', color: '#ff9ff3' },
  { key: 'nsecMissingNum', name: 'NSEC缺失', color: '#54a0ff' },
  { key: 'noZoneKeyNum', name: '无区域密钥', color: '#5f27cd' }
]

// 获取数据并初始化图表
const initChart = async () => {
  try {
    loading.value = true
    
    // 如果已有图表实例，先清理
    if (window.errorChartInstance) {
      window.errorChartInstance.dispose()
      window.errorChartInstance = null
    }

    // 清空容器
    if (chart.value) {
      chart.value.innerHTML = ''
    }

    // 调用后端API获取错误趋势数据
    const response = await dashboardApi.getErrorsTendency()
    
    if (response.code === 200 && response.data) {
      // 转换数据格式
      chartData.value = response.data.map(item => ({
        date: item.scanDate,
        unsupportedDsNum: item.unsupportedDsNum || 0,
        unsupportedDnskeyNum: item.unsupportedDnskeyNum || 0,
        dnskeyMissingNum: item.dnskeyMissingNum || 0,
        rrsigMissingNum: item.rrsigMissingNum || 0,
        signatureNotValidNum: item.signatureNotValidNum || 0,
        signatureExpiredNum: item.signatureExpiredNum || 0,
        nsecMissingNum: item.nsecMissingNum || 0,
        noZoneKeyNum: item.noZoneKeyNum || 0
      }))
    } else {
      console.warn('获取错误趋势数据失败:', response.message)
      chartData.value = []
    }

    const myChart = echarts.init(chart.value, null, {
      renderer: 'svg',
      width: 'auto',
      height: 'auto'
    })

    // 保存实例到全局变量
    window.errorChartInstance = myChart

    // 准备图表数据
    const dates = chartData.value.map(item => item.date).reverse()
    const series = errorTypes.map(errorType => ({
      name: errorType.name,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2,
        color: errorType.color
      },
      itemStyle: {
        color: errorType.color,
        borderColor: errorType.color,
        borderWidth: 2
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: errorType.color + '40' },
            { offset: 1, color: errorType.color + '10' }
          ]
        }
      },
      data: chartData.value.map(item => item[errorType.key]).reverse()
    }))

    const option = {
      animation: true,
      animationDuration: 1000,
      title: {
        text: 'DNSSEC错误趋势分析',
        left: 'center',
        top: '10px',
        textStyle: {
          color: 'white',
          fontSize: 16,
          fontWeight: 600
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1,
        textStyle: {
          color: 'white'
        },
        formatter: function(params) {
          let result = `<div style="padding: 8px;"><div style="font-weight: bold; margin-bottom: 8px;">${params[0].axisValue}</div>`
          params.forEach(param => {
            result += `<div style="margin: 2px 0;"><span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 8px;"></span>${param.seriesName}: ${param.value}</div>`
          })
          result += '</div>'
          return result
        }
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        left: 'center',
        top: '35px',
        itemWidth: 12,
        itemHeight: 8,
        itemGap: 15,
        textStyle: {
          color: 'white',
          fontSize: 11
        },
        pageIconColor: 'white',
        pageIconInactiveColor: 'rgba(255, 255, 255, 0.3)',
        pageTextStyle: {
          color: 'white'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '8%',
        top: '80px',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates,
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 10,
          rotate: 45
        },
        axisTick: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisLabel: {
          color: 'rgba(255, 255, 255, 0.8)',
          fontSize: 10
        },
        axisTick: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            type: 'dashed'
          }
        }
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100
        },
        {
          type: 'slider',
          start: 0,
          end: 100,
          height: 20,
          bottom: 10,
          textStyle: {
            color: 'white'
          },
          borderColor: 'rgba(255, 255, 255, 0.3)',
          fillerColor: 'rgba(76, 201, 240, 0.2)',
          handleStyle: {
            color: '#4cc9f0'
          }
        }
      ],
      toolbox: {
        show: true,
        orient: 'horizontal',
        itemSize: 14,
        itemGap: 8,
        showTitle: true,
        top: '10px',
        right: '10px',
        iconStyle: {
          borderColor: 'white'
        },
        emphasis: {
          iconStyle: {
            borderColor: '#4cc9f0'
          }
        },
        feature: {
          saveAsImage: {
            show: true,
            type: 'png',
            name: 'dnssec-error-trends',
            backgroundColor: 'transparent'
          },
          dataView: {
            show: true,
            readOnly: false,
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            textColor: 'white'
          },
          magicType: {
            show: true,
            type: ['line', 'bar', 'stack']
          },
          restore: {
            show: true
          }
        }
      },
      series: series
    }

    myChart.setOption(option)

    // 响应式处理
    const handleResize = () => {
      if (myChart && !myChart.isDisposed()) {
        myChart.resize()
      }
    }

    window.addEventListener('resize', handleResize)
    
    // 清理函数
    const cleanup = () => {
      window.removeEventListener('resize', handleResize)
      if (myChart && !myChart.isDisposed()) {
        myChart.dispose()
      }
    }

    // 保存清理函数到组件实例
    chart.value._cleanup = cleanup

  } catch (error) {
    console.error('初始化错误趋势图表失败:', error)
    
    // 如果是401错误，不显示错误消息，让响应拦截器处理跳转
    if (error.code === 401) {
      console.log('Token过期，响应拦截器将处理跳转')
      return
    }
    
    chartData.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  initChart()
})

// 组件卸载时清理
onUnmounted(() => {
  if (chart.value && chart.value._cleanup) {
    chart.value._cleanup()
  }
  if (window.errorChartInstance) {
    window.errorChartInstance.dispose()
    window.errorChartInstance = null
  }
})
</script>

<template>
  <div ref="chart" class="error-chart"></div>
</template>

<style scoped>
.error-chart {
  width: 100%;
  height: 100%;
  position: absolute;
}
</style>